package com.ruoyi.machine.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.machine.EmpMachine;
import com.ruoyi.common.core.domain.store.EmpStoreVo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.machine.domain.vo.EmpMachineVo;
import com.ruoyi.machine.domain.vo.MachineListVo;
import com.ruoyi.machine.mapper.EmpMachineMapper;
import com.ruoyi.machine.service.IEmpMachineService;
import com.ruoyi.store.mapper.EmpStoreMapper;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.Validator;
import java.util.Date;
import java.util.List;

/**
 * 机台列表Service业务层处理
 *
 * @author 黄字添
 * @date 2023-12-25
 */
@Service
public class EmpMachineServiceImpl implements IEmpMachineService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private EmpMachineMapper empMachineMapper;

    @Autowired
    protected Validator validator;

    @Override
    public EmpMachineMapper getEmpMachineMapper() {
        return empMachineMapper;
    }

    @Override
    public Long[] getMachineTypeByStoreID(EmpMachine empMachine) {
        return empMachineMapper.getMachineTypeByStoreID(empMachine.getStoreID());
    }

    /**
     * 查询机台详情
     *
     * @param MachineID 机台列表主键
     * @return 机台列表
     */
    @Override
    public EmpMachine selectEmpMachineByMachineID(Long MachineID) {
        return empMachineMapper.selectEmpMachineByMachineID(MachineID);
    }

    /**
     * 查询机台列表列表
     *
     * @param empMachine 机台列表
     * @return 机台列表
     */
    @Override
    @DataScope(deptAlias = "m", userAlias = "m")
    public List<EmpMachine> selectEmpMachineList(EmpMachineVo empMachine) {
        return empMachineMapper.selectEmpMachineList1(empMachine);
    }
    
    /**
     * 查询机台列表列表
     *
     * @param empMachine 机台列表
     * @return 机台列表
     */
    @Override
    public EmpMachine selectMachineInfo(Long machineID) {
        List<EmpMachine> list = empMachineMapper.selectMachineInfo(machineID);
        // 因为是按ID查询，理论上列表不为空时只有一个元素，其中包含了设备列表
        return (list != null && !list.isEmpty()) ? list.get(0) : null;
    }

    /**
     * 查询机台列表列表
     *
     * @param empMachine 机台列表
     * @return 机台列表
     */
    @Override
    public List<EmpMachine> selectEmpMachineNoUseList(EmpMachineVo empMachine) {
        return empMachineMapper.selectEmpMachineNoUseList(empMachine);
    }
    
    /**
     * 查询所有机台列表
     *
     * @param empMachine 机台列表
     * @return 机台列表 
     */
    @Override
    public List<EmpMachine> selectEmpMachineAllUseList(EmpMachineVo empMachine) {
        return empMachineMapper.selectEmpMachineAllUseList(empMachine);
    }
    
    /**
     * 查询机台当前状态
     *
     * @param machineID 机台列表主键
     * @return 状态值
     */
    @Override
    public Integer selectStatus(Long machineID) {
        return empMachineMapper.selectStatus(machineID);
    }

    /**
     * 新增机台列表
     *
     * @param empMachine 机台列表
     * @return 结果
     */
    @Autowired
    private EmpStoreMapper empStoreMapper;
    @Override
    public int insertEmpMachine(EmpMachine empMachine) {
        if(empMachine.getStoreName()!=null){
            EmpStoreVo store = empStoreMapper.findStoreByName(empMachine.getStoreName());
            empMachine.setUserId(store.getUserId());
            empMachine.setDeptId(store.getDeptId());
        }
        return empMachineMapper.insertEmpMachine(empMachine);
    }

    /**
     * 修改机台列表
     *
     * @param empMachine 机台列表
     * @return 结果
     */
    @Override
    public int updateEmpMachine(EmpMachine empMachine) {
        return empMachineMapper.updateEmpMachine(empMachine);
    }

    /**
     * 批量删除机台列表
     *
     * @param MachineIDs 需要删除的机台列表主键
     * @return 结果
     */
    @Override
    public int deleteEmpMachineByMachineIDs(Long[] MachineIDs) {
        return empMachineMapper.deleteEmpMachineByMachineIDs(MachineIDs);
    }

    /**
     * 删除机台列表信息
     *
     * @param MachineID 机台列表主键
     * @return 结果
     */
    @Override
    public int deleteEmpMachineByMachineID(Long MachineID) {
        return empMachineMapper.deleteEmpMachineByMachineID(MachineID);
    }


    /**
     * 导入机台列表信息
     *
     * @param machineList   机台列表
     * @param updateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName      操作用户
     * @return
     */
    @Override
    public String importData(List<EmpMachine> machineList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(machineList) || machineList.size() == 0) {
            throw new ServiceException("导入机台列表数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (EmpMachine machine : machineList) {
            try {
                // 验证是否存在这个机台
                EmpMachine u = empMachineMapper.selectEmpMachineByMachineID(machine.getMachineID());
                if (StringUtils.isNull(u)) { //不存在
                    BeanValidators.validateWithException(validator, machine);
                    machine.setCreatedBy(operName);
                    machine.setCreatedTime(new Date());
                    empMachineMapper.insertEmpMachine(machine);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、机台ID: " + machine.getMachineID() + " 导入成功");
                } else if (updateSupport) { //存在，但支持更新
                    BeanValidators.validateWithException(validator, machine);
                    machine.setCreatedBy(u.getCreatedBy());
                    machine.setCreatedTime(u.getCreatedTime());
                    machine.setUpdatedBy(operName);
                    machine.setUpdatedTime(new Date());
                    empMachineMapper.updateEmpMachine(machine);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、机台ID: " + machine.getMachineID() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、机台ID: " + machine.getMachineID() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、机台ID: " + machine.getMachineID() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public List<EmpStoreVo> selectEmpStoreList() {
        return empMachineMapper.selectEmpStoreList();
    }

    @Override
    public List<EmpMachine> selectEmpMachineListByTypeAndStore(EmpMachine empMachine) {
        return empMachineMapper.selectEmpMachineListByTypeAndStore(empMachine);
    }

    @Override
    public int handleStatusDown(Long machineID) {
        return empMachineMapper.updateStatusDown(machineID);
    }

    @Override
    public int handleStatusMaintenance(Long machineID) {
        return empMachineMapper.updateStatusMaintenance(machineID);
    }

    @Override
    public int addOnlineNumber(Long machineID) {
        return empMachineMapper.addOnlineNumber(machineID);
    }

    @Override
    public int reduceOnlineNumber(Long machineID) {
        return empMachineMapper.reduceOnlineNumber(machineID);
    }

    @Override
    public EmpMachine getOneByID(Long machineID) {
        return empMachineMapper.selectEmpMachineByMachineID(machineID);
    }

    @Override
    public AjaxResult getMachineList(Long storeID) {
        List<MachineListVo> list = empMachineMapper.getMachineList(storeID);
        return AjaxResult.success(list);
    }

    @Override
    public int updateStatusLock(Long machineID) {
        return empMachineMapper.updateStatusLock(machineID);
    }

    @Override
    public int updateStatusUnLock(Long machineID) {
        return empMachineMapper.updateStatusUnLock(machineID);
    }

	@Override
	public List<EmpMachine> selectAppMachineList(EmpMachineVo empMachine) {
		return empMachineMapper.selectAppMachineList(empMachine);
	}
}
